<?php

/**
 * Class Module_Task_Repair
 *
 */
class Module_Task_Repair
{
    //提交修复
    public static function submitRepairHandler($data){
        //校验必填参数
        if(!Lib_Notice::checkData($data,['caseId','batchId','repairType','creatId','mediationOrganId'])) {
            Func_Log::write('submitRepair', 'data lack mast param', 'res= ' . json_encode($data));
            return ['code' => 4001, 'message' => '缺少必要参数', 'data' => []];
        }
        $caseId = $data['caseId'];
        $case = Module_Mediate_Case::getInstance()->getOne(['sysStatus','litigantName','cardId'],["id = {$caseId}"],true);
        if (empty($case)) {
            Func_Log::write('submitRepair', 'case is empty', 'res= ' . json_encode($data));
            return ['code' => 4002, 'message' => '案件信息不存在', 'data' => []];
        }
        if($case['sysStatus'] != 1){
            Func_Log::write('submitRepair', 'case sysStatus error', 'data= ' . json_encode($data));
            return ['code' => 4002, 'message' => '案件状态异常', 'data' => []];
        }
//        $mobiles = Module_Mediate_CaseLitigant::getInstance()->getAllBySearch(['telephone'],['where'=>["cardId='{$case['cardId']}'",'group'=>'telephone']]);
//        $knownMobile = [];
//        if($mobiles) {
//            foreach ($mobiles as $val){
//                //支持3个
//                if(count($knownMobile) >= 3){
//                   break;
//                }
//                $knownMobile[] = hash("sha256", $val['telephone']);
//
//            }
//        }
        $knownMobile = Module_Mediate_CaseLitigant::getInstance()->getOne([],["caseId = {$caseId}"]);
        if($knownMobile){
            $knownMobile = hash("sha256", $knownMobile['telephone']);
        }else{
            $knownMobile = '';
        }
        $res = Module_Repair_RepairRecord::getInstance()->singleInsert(
            [
                'repairType' => $data['repairType'],
                'creatId' => $data['creatId'],
                'mediationOrganId' => $data['mediationOrganId'],
                'repairName' => $case['litigantName'],
                'idCard' => $case['cardId'],
                'repairStatus' => 1,
                'batchId' => $data['batchId'],
                'creatTime' => time(),
                'sha256idCard' => hash("sha256", $case['cardId']),
                //'knownMobile' => empty($knownMobile) ? '' : implode(',', $knownMobile)
                'knownMobile' => $knownMobile
            ]
        );
        if(!$res){
            Func_Log::write('submitRepair', 'submit fail', 'data= ' . json_encode($data));
            return ['code' => 5000, 'message' => '数据添加失败', 'data' => []];
        }
        //暂无
        return ['code' => 200, 'message' => 'success', 'data' => []];

    }

    //提交运营商
    public static function submitISPHandler($data){
        //校验必填参数
        if(!Lib_Notice::checkData($data,['batchId','repairType'])) {
            Func_Log::write('submitRepair', 'data lack mast param', 'res= ' . json_encode($data));
            return ['code' => 4001, 'message' => '缺少必要参数', 'data' => []];
        }
        //查询需要复联数据
        $record = Module_Repair_RepairRecord::getInstance()->getAllBySearch(['repairName','sha256idCard','knownMobile'], ['where'=>["batchId={$data['batchId']}",'repairStatus = 1']]);
        if(empty($record)){
            Func_Log::write('submitRepair', 'empty repair record', 'res= ' . json_encode($data));
            return ['code' => 4001, 'message' => '缺少必要参数', 'data' => []];
        }
        $repairData = [];
        $day30 = time()-(30*86400);
        foreach ($record as $val){
            //判断30天内是否有成功修复记录
            $hitory = Module_Repair_RepairResult::getInstance()->getOne(['id'],["sha256idCard = '{$val['sha256idCard']}'","repairType = {$data['repairType']}","repairTime>=$day30"]);
            if(empty($hitory)){
                //一天内重复提交
                if(Lib_Redis_String::get($val['sha256idCard'].'_'.$data['repairType'])){
                    Func_Log::write('submitRepair', 'already submit', 'sha256idCard = '.$val['sha256idCard']);
                    continue;
                }
                $repairData[] = $val;
            }
        }
        if(empty($repairData)){
            Module_Repair_RepairBatch::getInstance()->singleUpdate(
                [
                    'id'=>$data['batchId'],
                    'repairStatus'=>2,
                    'desc'=>'无符合条件修复数据/数据已提交过',
                ]
            );
            Func_Log::write('submitRepair', 'empty repairData', 'batchId = '.$data['batchId'].' res= ' . json_encode($record));
            return ['code' => 200, 'message' => 'success', 'data' => []];
        }
        $res = Lib_Repair_Main::repair([
            'pass'=> $data['repairType'] == 1 ? "YiDong" : "LianTong",
            'data'=>[
                'businessData'=>[
                    'rerairId'=>$data['batchId'],
                    'repairType'=>$data['repairType'],
                ],
                'repairData'=>$repairData,
            ]
        ]);

        if($res['code'] != 200){
            Module_Repair_RepairBatch::getInstance()->singleUpdate(
                [
                    'id'=>$data['batchId'],
                    'repairStatus'=>2,
                    'desc'=>$res['message'],
                ]
            );
            Func_Log::write('submitRepair', 'submit ISP error', 'batchId = '.$data['batchId'].' res= ' . json_encode($res));
            return ['code' => 200, 'message' => 'success', 'data' => []];
        }
        //提交成功加入队列
        foreach ($repairData as $val){
            Lib_Redis_String::setex($val['sha256idCard'].'_'.$data['repairType'],86400,$val['sha256idCard']);
        }
        Func_Log::write('submitRepair', 'submit ISP success', 'batchId = '.$data['batchId'].' res= ' . json_encode($res));
        $res = Module_Repair_RepairBatch::getInstance()->singleUpdate(
            [
                'id'=>$data['batchId'],
                'batchNo' => $res['data']['batchNo'],
            ]
        );
        if(!$res){
            Func_Log::write('submitRepair', 'submit success update batchNo error', 'batchId = '.$data['batchId'].' res= ' . json_encode($res));
            return ['code' => 200, 'message' => 'success', 'data' => []];
        }
        $res = Module_Repair_RepairRecord::getInstance()->singleUpdate(
            [
                'batchId'=>$data['batchId'],
                'repairStatus' => 2
            ],
            'batchId'
        );
        if(!$res){
            Func_Log::write('submitRepair', 'submit success update batchNo error', 'batchId = '.$data['batchId'].' res= ' . json_encode($res));
            return ['code' => 200, 'message' => 'success', 'data' => []];
        }
        return ['code' => 200, 'message' => 'success', 'data' => []];
    }
    //联通复联结果
    public static function ltResultHandler($data)
    {
        if (!$data) {
            return ['code' => 4000, 'message' => '缺少参数', 'data' => []];
        }
        try {
            //修复失败
            if(empty($data['repairStatus']) || empty($data['batchNo']) || empty($data['batchId']) || empty($data['idCard'])){
                Func_Log::write('repair',   'liantong','query repair result -- repair data error '.'responsedata : '. json_encode($data));
                return ['code' => 4000, 'message' => '缺少参数', 'data' => []];
            }
            //查询修复记录
            $repair_record = Module_Repair_RepairRecord::getInstance()->getOne(['id','idCard','repairName'],["batchId={$data['batchId']}","sha256idCard='{$data['idCard']}'"]);
            //查询对应案件
            $caseIds = '';
            if($repair_record){
                $cases = Module_Mediate_Case::getInstance()->getAllBySearch(['id'],['where'=>["cardId='{$repair_record['idCard']}'",'sysStatus = 1']]);
                if($cases){
                    $caseIds = implode(',',array_column($cases,'id'));
                }
            }
            //修复  不可修复，入库
            if($data['repairStatus'] != 'RPS002'){
                Func_Log::write('repair',   'liantong','query repair result -- repair fail '. 'responsedata : '. json_encode($data));
                //修复失败入库
                if($repair_record) {
                    self::updateRepairData(2, $repair_record['id'], $caseIds, 'liantong');
                }
                return ['code' => 200, 'message' => 'success', 'data' => []];
            }
            //可修复  调用 查询修复结果接口
            $request = [
                'batchNo' => $data['batchNo'],
                'idCard' => $data['idCard'],
            ];
            $query_result = Lib_Repair_Implement_LianTong::getInstance()->queryPhoneNum($request);
            if($query_result['code'] != '000' ){//请求返回异常
                Func_Log::write('repair',   'liantong','query repair result -- error response '.'responsedata : '. json_encode($query_result));
                return ['code' => 4000, 'message' => '查询失败', 'data' => []];

            }
            if(empty($query_result['data'])){//修复失败
                self::updateRepairData(1, $repair_record['id'], $caseIds, 'liantong');
                Func_Log::write('repair',   'liantong','query repair result -- data empty '.'responsedata : '. json_encode($query_result));
                return ['code' => 4000, 'message' => '修复数据为空', 'data' => []];
            }
            //循环入库成功入库 后期再改
            foreach($query_result['data'] as $val){
                $res = Module_Repair_RepairResult::getInstance()->singleInsert([
                    'idCard'=>empty($repair_record['idCard']) ? '' : $repair_record['idCard'],
                    'repairName'=>empty($repair_record['repairName']) ? '' : $repair_record['repairName'],
                    'batchNo' => $data['batchNo'],
                    'repairTime' => time(),
                    'repairType' => 2,
                    'repairmobile' => $val,
                    'sha256idCard' => strtolower($data['idCard'])
                ]);
            }
            if(!$res){
                Func_Log::write('repair',   'query repair result -- add fail', 'data : '. json_encode($query_result));
                return ['code' => 5001, 'message' => '数据入库失败', 'data' => []];
            }
            Func_Log::write('repair',   'liantong','query repair result -- success'.'data : '. json_encode($query_result));
            self::updateRepairData(1, $repair_record['id'], $caseIds, 'liantong');
            return ['code' => 200, 'message' => 'success', 'data' => []];

        } catch (Exception $e) {
            Func_Log::write('repair',   'liantong','query repair error  --'. $e->getMessage().'responsedata : '. json_encode($data));
            return ['code' => 400, 'message' => '运行异常', 'data' => []];
        }
    }
    //移动复联结果
    public static function ydResultHandler($data)
    {
        if (!$data) {
            return ['code' => 4000, 'message' => '缺少参数', 'data' => []];
        }
        try {
            //修复失败
            if(empty($data['repairStatus']) || empty($data['batchNo']) || empty($data['sha256idCard']) || empty($data['idCard'])  || empty($data['repairName']) || empty($data['recordId'])){
                Func_Log::write('repair',   'yidong','query repair result -- repair data error '.'responsedata : '. json_encode($data));
                return ['code' => 4000, 'message' => '缺少参数', 'data' => []];
            }
            //查询对应案件
            $caseIds = '';
            $cases = Module_Mediate_Case::getInstance()->getAllBySearch(['id'],['where'=>["cardId='{$data['idCard']}'",'sysStatus = 1']]);
            if($cases){
                $caseIds = implode(',',array_column($cases,'id'));
            }
            //修复失败
            if($data['repairStatus'] != 3){
                Func_Log::write('repair',   'yidong','query repair result -- repair fail '. 'responsedata : '. json_encode($data));
                //修复失败入库
                self::updateRepairData(2, $data['recordId'], $caseIds, 'yidong');
                return ['code' => 200, 'message' => 'success', 'data' => []];
            }
            //修复成功
            if(empty($data['phoneList'])){
                Func_Log::write('repair',   'yidong','query repair result -- error data '. 'responsedata : '. json_encode($data));
                return ['code' => 400, 'message' => 'success', 'data' => []];
            }
            foreach($data['phoneList'] as $val){
                if(empty($val['phoneSeqNo'])){
                    Func_Log::write('repair',   'yidong','query repair result -- empty repairPhoneID'. 'responsedata : '. json_encode($data));
                    continue;
                }
                $res = Module_Repair_RepairResult::getInstance()->singleInsert([
                    'repairName'=>empty($data['repairName']) ? '' : $data['repairName'],
                    'idCard'=>empty($data['idCard']) ? '' : $data['idCard'],
                    'batchNo' => $data['batchNo'],
                    'repairTime' => time(),
                    'repairType' => 1,
                    'sha256idCard' => strtolower($data['sha256idCard']),
                    'resultId' =>  $data['resultId'],
                    'repairmobile' =>  $val['phoneSeqNo'],
                    'validityTime' => time() + (90*86400),//有效期3个月
                ]);
            }
            if(!$res){
                Func_Log::write('repair',   'query repair result -- add fail', 'data : '. json_encode($data));
                return ['code' => 5001, 'message' => '数据入库失败', 'data' => []];
            }
            Func_Log::write('repair',   'liantong','query repair result -- success'.'data : '. json_encode($data));
            self::updateRepairData(1, $data['recordId'], $caseIds, 'yidong');
            return ['code' => 200, 'message' => 'success', 'data' => []];

        } catch (Exception $e) {
            Func_Log::write('repair',   'liantong','query repair error  --'. $e->getMessage().'responsedata : '. json_encode($data));
            return ['code' => 400, 'message' => '运行异常', 'data' => []];
        }
    }
    //再芮复联结果
    public static function zrResultHandler($data)
    {
        if (!$data) {
            return ['code' => 4000, 'message' => '缺少参数', 'data' => []];
        }
        try {
            //修复失败repairType
            if(empty($data['repairType']) || empty($data['repairStatus']) || empty($data['batchNo']) || empty($data['sha256idCard']) || empty($data['idCard'])  || empty($data['repairName']) || empty($data['recordId'])){
                Func_Log::write('repair',   'zairui','query repair result -- repair data error '.'responsedata : '. json_encode($data));
                return ['code' => 4000, 'message' => '缺少参数', 'data' => []];
            }
            $pass = $data['repairType'] == 1 ? 'yidong' : 'liantong';
            //查询对应案件
            $caseIds = '';
            $cases = Module_Mediate_Case::getInstance()->getAllBySearch(['id'],['where'=>["cardId='{$data['idCard']}'",'sysStatus = 1']]);
            if($cases){
                $caseIds = implode(',',array_column($cases,'id'));
            }
            //修复失败
            if($data['repairStatus'] != 3){
                Func_Log::write('repair',   'zairui','query repair result -- repair fail '. 'responsedata : '. json_encode($data));
                //修复失败入库
                self::updateRepairData(2, $data['recordId'], $caseIds, $pass);
                return ['code' => 200, 'message' => 'success', 'data' => []];
            }
            //修复成功
            if(empty($data['telXData'])){
                Func_Log::write('repair',   'zairui','query repair result -- error data '. 'responsedata : '. json_encode($data));
                return ['code' => 400, 'message' => 'success', 'data' => []];
            }
            foreach($data['telXData'] as $val){
                if(empty($val['repairPhoneID'])){
                    Func_Log::write('repair',   'zairui','query repair result -- empty repairPhoneID'. 'responsedata : '. json_encode($data));
                    continue;
                }
                $res = Module_Repair_RepairResult::getInstance()->singleInsert([
                    'repairName'=>empty($data['repairName']) ? '' : $data['repairName'],
                    'idCard'=>empty($data['idCard']) ? '' : $data['idCard'],
                    'batchNo' => $data['batchNo'],
                    'repairTime' => time(),
                    'repairType' => $data['repairType'],
                    'sha256idCard' => strtolower($data['sha256idCard']),
                    'resultId' =>  $val['repairPhoneID'],
                    'repairmobile' => empty($val['extNumber']) ? $val['repairPhoneID'] : $val['extNumber'],
                    'validityTime' => time() + (90*86400),//有效期3个月
                ]);
            }
            if(!$res){
                Func_Log::write('repair',   'zairui query repair result -- add fail', 'data : '. json_encode($data));
                return ['code' => 5001, 'message' => '数据入库失败', 'data' => []];
            }
            Func_Log::write('repair',   'zairui','query repair result -- success'.'data : '. json_encode($data));
            self::updateRepairData(1, $data['recordId'], $caseIds, $pass);
            return ['code' => 200, 'message' => 'success', 'data' => []];

        } catch (Exception $e) {
            Func_Log::write('repair',   'zairui','query repair error  --'. $e->getMessage().'responsedata : '. json_encode($data));
            return ['code' => 400, 'message' => '运行异常', 'data' => []];
        }
    }
    //更新批次信息
    public static function updateBatchHandler($data){
        //查询批次下还是修复中的记录
        if(empty($data['batchId'])|| empty($data['repairType']) ||  empty($data['batchNo'])){
            Func_Log::write('repair',   'updateBatch','query repair result -- repair data error '.'responsedata : '. json_encode($data));
            return ['code' => 4000, 'message' => '缺少参数', 'data' => []];
        }
        $repair_record = Module_Repair_RepairRecord::getInstance()->getAllBySearch(['id','idCard','repairName','sha256idCard'],['where' => ["batchId={$data['batchId']}","repairStatus=2"]]);
        if($repair_record){
            foreach ($repair_record as $record) {
                $caseIds ='';
                $pass = $data['repairType'] == 1 ? 'yidong' : 'liantong';
                $cases = Module_Mediate_Case::getInstance()->getAllBySearch(['id'],['where'=>["cardId='{$record['idCard']}'",'sysStatus = 1']]);
                if($cases){
                    $caseIds = implode(',',array_column($cases,'id'));
                }
                //先看是否是已经修复过，排除了
                $day90 = time() - (90 * 86400);
                //循环判断90天内是否有成功修复记录
                $hitory = Module_Repair_RepairResult::getInstance()->getOne(['id'], ["sha256idCard = '{$record['sha256idCard']}'", "repairType = {$data['repairType']}", "repairTime>=$day90"]);
                //有记录，按照成功处理
                if($hitory){
                    self::updateRepairData(1, $record['id'], $caseIds, $pass);
                }else{//查询失败处理
                    if($pass == 'liantong'){
                        $request = [
                            'batchNo' => $data['batchNo'],
                            'idCard' => $record['sha256idCard'],
                        ];
                        $query_result = Lib_Repair_Implement_LianTong::getInstance()->queryPhoneNum($request);
                        if($query_result['code'] != '000' ){//请求返回异常
                            Func_Log::write('repair',   'liantong','updateBatch query repair result -- error response '.'responsedata : '. json_encode($query_result));
                            continue;
                        }
                        if(empty($query_result['data'])){//修复失败
                            self::updateRepairData(1, $record['id'], $caseIds, 'liantong');
                            Func_Log::write('repair',   'liantong','updateBatch query repair result -- data empty '.'responsedata : '. json_encode($query_result));
                            continue;
                        }
                        //循环入库成功入库 后期再改
                        foreach($query_result['data'] as $val){
                            $repair_data['middle_number'] = $val;//修复中间号码
                            $res = Module_Repair_RepairResult::getInstance()->singleInsert([
                                'idCard'=>empty($record['idCard']) ? '' : $record['idCard'],
                                'repairName'=>empty($record['repairName']) ? '' : $record['repairName'],
                                'batchNo' => $data['batchNo'],
                                'repairTime' => time(),
                                'repairType' => 2,
                                'repairmobile' => $val,
                                'sha256idCard' => $record['sha256idCard']
                            ]);
                        }
                        if(!$res){
                            Func_Log::write('repair',   'updateBatch query repair result -- add fail', 'data : '. json_encode($repair_data));
                            continue;
                        }
                        Func_Log::write('repair',   'liantong','query repair result -- success'.'data : '. json_encode($repair_data));
                        self::updateRepairData(1, $record['id'], $caseIds, 'liantong');
                    }

                }
            }
        }
        $success_num = Module_Repair_RepairRecord::getInstance()->getAllBySearch(['count(id) as num'],['where' => ["batchId={$data['batchId']}","repairStatus=3"]]);
        $res = Module_Repair_RepairBatch::getInstance()->singleUpdate([
            'id' => $data['batchId'],
            'repairStatus' => 4,
            'completeTime' => time(),
            'successNum' => empty($success_num[0]['num']) ? 0 : $success_num[0]['num'],
        ]);
        if(!$res){
            Func_Log::write('repair',   'updateBatch error result', 'data : '. json_encode($data));
            return ['code' => 4000, 'message' => '缺少参数', 'data' => []];
        }
        Func_Log::write('repair',   'updateBatch success', 'data : '. json_encode($data));

        return ['code' => 200, 'message' => 'success', 'data' => $data];



    }
    //修改记录和案件修复状态
    private static function updateRepairData($repairStatus,$repairRecordId=0,$caseIds='',$pass){
        $RepairStatusField = $pass == 'liantong' ? 'ltRepairStatus' : 'ydRepairStatus';
        if($repairRecordId){
            $res = Module_Repair_RepairRecord::getInstance()->singleUpdate([
                'id' => $repairRecordId,
                'repairStatus' => $repairStatus == 1 ? 3 : 4 ,
                'repairTime' => time()
            ]);
            if(!$res){
                Func_Log::write('repair',   $pass,'query repair result -- RepairRecord update fail '.' repairStatus : '.$data['repairStatus'].' record_id : '. $repair_record['id']);
            }
        }
        //更新案件信息
        if($caseIds){
            $saveData = [
                $RepairStatusField => $repairStatus,
                'updateTime' => time()
            ];
            $res = Module_Mediate_Case::getInstance()->saveByIds($saveData, $caseIds);
            if(!$res){
                Func_Log::write('repair',   $pass,'query repair result -- ltRepairStatus update fail '.' repairStatus : '.$data['repairStatus'].' caseIds : '. $caseIds);
            }
        }
    }
}
